package com.sskj.hhhjys;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.DisposUtil;
import com.sskj.hhhjys.bean.NewStock;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.ColorEnum;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author Hey
 * Create at  2019/05/10
 */
public class MarketFragment extends BaseFragment<MarketPresenter> {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.ivBack)
    LinearLayout ivBack;
    @BindView(R.id.right_tv)
    TextView rightTv;
    @BindView(R.id.records_list)
    RecyclerView recordsList;
    SlimAdapter<CoinBean> slimAdapter;
    HashMap<String, Integer> iconMap = new HashMap<>();
    private Map<String, Disposable> timeMap = new HashMap<>();

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_market;
    }

    @Override
    public MarketPresenter getPresenter() {
        return new MarketPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        ivBack.setVisibility(View.GONE);
        tvTitle.setText(App.INSTANCE.getString(R.string.app_marketFragment1_h));
        iconMap.put("btc_usdt", R.mipmap.app_icon_btc);
        iconMap.put("eth_usdt", R.mipmap.app_icon_eth);
        iconMap.put("eos_usdt", R.mipmap.app_icon_eos);
        iconMap.put("etc_usdt", R.mipmap.app_icon_etc);
        iconMap.put("ltc_usdt", R.mipmap.app_icon_ltc);
        iconMap.put("xrp_usdt", R.mipmap.app_icon_xrp);
        iconMap.put("bch_usdt", R.mipmap.app_icon_bch);
        iconMap.put("dash_usdt", R.mipmap.app_icon_dash);
        recordsList.setLayoutManager(new LinearLayoutManager(getContext()));
        slimAdapter = SlimAdapter.create().register(R.layout.app_market_item, new SlimInjector<CoinBean>() {
            @Override
            public void onInject(CoinBean data, IViewInjector injector, List list) {
                injector.background(R.id.viewCoin, ContextCompat.getDrawable(App.INSTANCE, iconMap.get(data.getCode()) == null ? R.mipmap.app_icon_btc : iconMap.get(data.getCode())))
                        .text(R.id.tvUSDT, data.getPrice())
                        .text(R.id.tvCode, data.getName().replace("_", "/").contains("/") ? data.getName().substring(0, data.getName().replace("_", "/").indexOf("/")) : data.getName())
                        .text(R.id.tvRate, data.isUp() ? ("+" + data.getChangeRate()) : data.getChangeRate())
                        .background(R.id.tvRate, ContextCompat.getDrawable(App.INSTANCE, data.isUp() ? R.drawable.app_shape_corner35_03c : R.drawable.app_shape_corner35_ff5))
                        .textColor(R.id.tvUSDT, data.getLight() ?
                                (getResources().getColor(data.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor())) :
                                getResources().getColor(R.color.app_8e9));
                injector.findViewById(R.id.item_layout).setOnClickListener(v -> {
                    ARouter.getInstance().build(RConfig.APP_MARKET).withString(Constans.CODE, data.getCode()).navigation();
                });
            }

        }).attachTo(recordsList);
    }


    @Override
    public void initData() {
        mPresenter.initWebSocket();
        mPresenter.getData();
    }

    public static MarketFragment newInstance() {
        MarketFragment fragment = new MarketFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCoin(CoinBean stockSocketBean) {
        if (slimAdapter == null || slimAdapter.getData() == null || slimAdapter.getData().size() == 0)
            return;

        if (slimAdapter != null) {
            Flowable.fromIterable(slimAdapter.getData())
                    .filter(item -> item.getCode().equals(stockSocketBean.getCode()))
                    .subscribe(item -> {
                        stockSocketBean.setLight(true);
                        int position = slimAdapter.getData().indexOf(item);
                        slimAdapter.getData().set(position, stockSocketBean);
                        slimAdapter.notifyItemChanged(position, 1);
                        DisposUtil.close(timeMap.get(item.getCode()));
                        Disposable subscribe = Flowable.timer(1000, TimeUnit.MILLISECONDS)
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(i -> {
                                    stockSocketBean.setLight(false);
                                    slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(stockSocketBean), 1);
                                });
                        timeMap.put(item.getCode(), subscribe);
                    }, e -> {
                    });
        }
    }

    public void setData(List<CoinBean> data) {
        slimAdapter.updateData(data);
    }
}
